package com.javasm.mingming.news.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.javasm.mingming.common.RedisKeys;
import com.javasm.mingming.news.dao.NewsDao;
import com.javasm.mingming.news.entity.News;
import com.javasm.mingming.news.service.NewsService;
import com.javasm.mingming.news.vo.NewsData;
import com.javasm.mingming.news.vo.NewsModel;
import com.javasm.mingming.news.vo.NewsResult;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * (News)表服务实现类
 *
 * @author makejava
 * @since 2025-01-16 09:47:16
 */
@Service("newsService")
public class NewsServiceImpl extends ServiceImpl<NewsDao, News> implements NewsService {

    @Resource
    RestTemplate restTemplate;
    @Resource
    RedisTemplate<String, Object> redisTemplate;

    @Override
    public List<NewsModel> syncNews() {
        String url = "https://apis.tianapi.com/toutiaohot/index?key=ed475d5faa4488028e9f5e369c77e1b5";
        NewsResult object = restTemplate.getForObject(url, NewsResult.class);
        NewsData result = object.getResult();
        List<NewsModel> list = result.getList();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String t = simpleDateFormat.format(new Date());
        //news:day:20250116
        String key = String.format(RedisKeys.NewsDayList, t);
        Collection<Object> collection = new ArrayList<>(list);
        redisTemplate.opsForList().rightPushAll(key, collection);
        //设置过期时间
        redisTemplate.expire(key, 2, TimeUnit.HOURS);

        return list;
    }

    @Override
    public List<NewsModel> queryList(Integer pageNum, Integer pageSize) {
        String key = String.format(
                RedisKeys.NewsDayList,
                new SimpleDateFormat("yyyyMMdd").format(new Date())
        );
        List<NewsModel> list;
        //查询 总条数
        Long total = redisTemplate.opsForList().size(key);
        int start = (pageNum - 1) * pageSize;

        if (total.longValue() <= 0L) {
            //redis中没有数据
            //同步数据
            list = syncNews();
            int end = Math.min(start + pageSize - 1, list.size() - 1);
            list = list.subList(start, end + 1);
        } else {
            int end = Math.min(start + pageSize - 1, total.intValue() - 1);
            List<Object> objectList = redisTemplate.opsForList().range(key, start, end);
            list = objectList.stream().map(o -> (NewsModel) o).collect(Collectors.toList());
        }
        return list;
    }
}

